import edu.princeton.cs.algs4.StdOut;
import edu.princeton.cs.algs4.StdRandom;
import edu.princeton.cs.algs4.StdStats;

// import edu.princeton.cs.algs4.Stopwatch;

public class PercolationStats {
    private double[] x;
    private double mu;
    private double sigma;
    private double confLo;
    private double confHi;

    public PercolationStats(int n, int t) {
        if (n <= 0 || t <= 0)
            throw new IllegalArgumentException();
        x = new double[t];
        int k = t;
        while (k-- > 0) {
            Percolation perc = new Percolation(n);
            int[] ids = StdRandom.permutation(n * n);
            for (int id : ids) {

                int i = id / n + 1;
                int j = id % n + 1;
                perc.open(i, j);
                ++x[k];
                if (perc.percolates()) {
                    break;
                }
            }

            x[k] /= n * n;
        }

        mu = StdStats.mean(x);

        if (t == 1) {
            sigma = Double.NaN;
            confLo = Double.NaN;
            confHi = Double.NaN;
        } else {
            sigma = StdStats.stddev(x);
            double tmp = 1.96 * sigma / Math.sqrt(t);
            confLo = mu - tmp;
            confHi = mu + tmp;
        }
    }

    public double mean() {
        return mu;
    }

    public double stddev() {
        return sigma;
    }

    public double confidenceLo() {
        return confLo;
    }

    public double confidenceHi() {
        return confHi;
    }

    public static void main(String[] args) { // test client (described below)
        if (args.length != 2)
            return;
        int n = Integer.parseInt(args[0]);
        int t = Integer.parseInt(args[1]);
        // Stopwatch sw = new Stopwatch();
        // double start = sw.elapsedTime();
        PercolationStats ps = new PercolationStats(n, t);
        StdOut.println(String.format("%-23s = %f", "mean", ps.mean()));
        StdOut.println(String.format("%-23s = %f", "stddev", ps.stddev()));
        StdOut.println(String.format("%-23s = [%.16f, %.16f]",
                "95% confidence interval", ps.confidenceLo(), ps.confidenceHi()));
        // StdOut.println(String.format("Running time: %f", sw.elapsedTime() -
        // start));
    }
}